﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommerceOne.Domains.Commons;
using CommerceOne.Domains.Entities;

namespace CommerceOne.Domains.Services
{
    public class SearchService : ISearchService
    {
        private readonly EfDbContext _context = new EfDbContext();

        public Commons.SearchProductResult SearchProduct(string keyword, List<Commons.IFilterParam> filterParam)
        {
            SearchProductResult searchResult = new SearchProductResult();
            SearchBuilder searchBuilder = new SearchBuilder("Select * from ProductSearchView");
            searchBuilder.OrderBy(" Id Desc");
            if (!string.IsNullOrEmpty(keyword))
            {
                IFilterParam keywordParam = new FilterParam<string>("ProductSearchView","Name", FilterType.Like, keyword);
                filterParam.Add(keywordParam);
            }

            FilterGroup group = new FilterGroup();
            group.AddRanger(filterParam.ToArray());
            searchBuilder.AddGroup(group);
            string query = searchBuilder.ToString();
            IEnumerable products = this._context.Database.SqlQuery(typeof(Product), query);

            searchResult.ResultItem = products.Cast<Product>().ToList();
            searchResult.Keyword = keyword;
            searchResult.MaxPrice = searchResult.ResultItem.Max(p => p.EnablePrice2 ? p.Price2 : p.Price1);
            searchResult.MinPrice = searchResult.ResultItem.Min(p => p.EnablePrice2 ? p.Price2 : p.Price1);

            return searchResult;
        }
    }
}
